package com.shimao.celnet.payment.controller.apitl;

import com.shimao.celnet.payment.controller.apinotcheck.CallOut_outPayRetInfoOutController;
import com.shimao.celnet.payment.form.IAppInterfaceForm;
import com.shimao.celnet.payment.form.PPayForm;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.service.IAppInterfaceService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 接受通联回调通知的接口，在移动端支付成功后，通联根据我们传入的notifyURL回调
 * 通联--->支付平台
 * 2017/12/14
 * christ
 */
@RestController
@RequestMapping(value = "/return")
public class CallIn_outPayRetInfoInController {
    //支付订单Service
    @Autowired
    private PPayService pPayService;
    //接口应用注册Service
    @Autowired
    private IAppInterfaceService iAppInterfaceService;

    @Autowired
    private CallOut_outPayRetInfoOutController callOut_outPayRetInfoOutController;


    @RequestMapping(value = "/payReturn", method = RequestMethod.POST)
    public String outPayRetInfoOut(HttpServletRequest request) throws IOException {
        PPayForm pPayFormResult = new PPayForm();
        //动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        TreeMap<String, String> params = getParams(request);
        System.out.println(".................>>>>>>>"+params.toString());
        try {
            //============1,根据流水单号trxid查询到对应的账单=================================
            pPayFormResult = pPayService.getInfoBytrxid(params.get("trxid"));
            //如果支付状态为已支付则直接返回
            if(FinalUtil.PAY_STATUS_SUSCSS.equals(pPayFormResult.getPayStatus())){
                //收到通知,返回success
                return String.valueOf("success".getBytes());
            }
            /**
             * 更新订单表的订单状态
             */
            PPay pPay = new PPay();
            pPay.setGuid(pPayFormResult.getGuid());//账单guid
            pPay.setPayStatus(FinalUtil.PAY_STATUS_SUSCSS);//支付状态
            pPay.setPayEndTime(String.valueOf(MyDateUtil.StrToDate(params.get("paytime"),MyDateUtil.format_yyyyMMddHHmmss).getTime()));//支付完成时间
            pPayService.update(pPay);
            //============2,根据账单上的app_key和interface_id查询出i_app_interface表的guid====
            IAppInterfaceForm iAppInterfaceForm = iAppInterfaceService.getInfoByAppIfKey(pPayFormResult.getAppKey(), pPayFormResult.getInterfaceId());
            //============3，根据guid，查询i_app_interface_asyn表所有需要回调的系统的returnUrl====
            System.out.println("guid"+iAppInterfaceForm.getGuid());
            List<IAppInterfaceForm> iAppInterfaceFormList = iAppInterfaceService.getRetAppInterface(iAppInterfaceForm.getGuid());
            //============4，循环对各系统进行通知=============================================
            if (pPayFormResult.getBusinessType().contains("pty")) {
                //=============5，判断是否来自物业的费用，如果是则推送消息给物业===============
                callOut_outPayRetInfoOutController.outPayRetInfoOutToWY(params, pPayFormResult);
            }
            for (IAppInterfaceForm iAppInterface : iAppInterfaceFormList) {
                //=============6，通知每个系统需要回调的接口==================================
                callOut_outPayRetInfoOutController.outPayRetInfoOutFromReq(params, pPayFormResult, iAppInterface, iAppInterface.getAppToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
            /**
             * 如果发生异常，则把状态更新为支付失败，从新回调
             */
            PPay pPay = new PPay();
            pPay.setGuid(pPayFormResult.getGuid());//账单guid
            pPay.setPayStatus(FinalUtil.PAY_STATUS_EXCEPTION);//支付状态 4回调异常
            pPay.setPayEndTime(String.valueOf(MyDateUtil.StrToDate(params.get("paytime"),MyDateUtil.format_yyyyMMddHHmmss).getTime()));//支付完成时间
            pPayService.update(pPay);
        } finally {
            //收到通知,返回success
            return String.valueOf("success".getBytes());

        }

    }

    /**
     * 动态遍历获取request的参数
     *
     * @param request
     * @return
     * @throws IOException
     */
    private TreeMap<String, String> getParams(HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for (Object key : reqMap.keySet()) {
            String value = ((String[]) reqMap.get(key))[0];
            System.out.println("-------打印输出--------" + key + ":" + value);
            map.put(key.toString(), value);
        }
        return map;
    }
}
